package main 

import (
	"bufio"
	"fmt"
	"os"
	"strconv"
	"strings"
	"mlib"
	"mp"
)

var lib *mlib.MusicManager
var id int = 1
var ctrl, signal chan int

func handleLibCommands(operation string, token string) {
	switch operation {
	case "list":
		for i := 0; i < lib.Len(); i++ {
			e, _ := lib.Get(i)
			fmt.Println(i + 1, ":", e.Name, e.Artist, e.Source, e.Type)
		}
	case "add":
		id++
		tokens := strings.Split(token, ",")
		if len(tokens) != 4 {
			fmt.Println("add parameter error.")
			return
		}
		for i, _ := range tokens {
			strings.Trim(tokens[i], " ")
		}
		lib.Add(&mlib.MusicEntry{strconv.Itoa(id), 
			tokens[0], tokens[1], tokens[2], tokens[3]})
	case "remove":
		lib.RemoveByName(token)
	default:
		fmt.Println("Unrecognized lib command: ", operation)
	}
}

func handlePlayCommand(name string) {
	_, e := lib.Find(name)
	if e == nil {
		fmt.Println("The music ", name, "does not exist.")
		return
	}

	mp.Play(e.Source, e.Type)
}


func main() {
	usageStr := `
        Enter folowing commands to control the player:
        list/ls/l           -- View the existing music lib
        add/a               -- Add a music to the lib
        remove/rm <name>    -- Remove the specified music from the lib
        play <name>         -- Play the specified music
		`
	fmt.Print(usageStr)

	lib = mlib.NewMusicManager()

	r := bufio.NewReader(os.Stdin)

	for {
		fmt.Println("\nEnter command-> ")
		rawline, _, _ := r.ReadLine()
		line := string(rawline)

		if line == "q" || line == "e" {
			break
		}

		commands := strings.Split(line, " ")

		if len(commands) == 0 {
			fmt.Print(usageStr)
		}

		switch commands[0] {
		case "list", "ls", "l":
			str := ""
			handleLibCommands("list", str)
		case "add", "a":
			fmt.Println("input <name>, <Artist>, <Source>, <type>")
			rawAddCommand, _, _ := r.ReadLine()
			addCommand := string(rawAddCommand)
			handleLibCommands("add", addCommand)
		case "remove", "rm":
			if len(commands) != 2 {
				fmt.Println("input remove/rm <name>")
				continue
			}
			handleLibCommands("remove", commands[1])
		case "play":
			if len(commands) != 2 {
				fmt.Println("input play <name>")
				continue
			}
			handlePlayCommand(commands[1])
		default:
			fmt.Println("Unrecognized command: ", commands[0])
			fmt.Print(usageStr)
		}
	}
}